import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cupertino_datetime_picker/flutter_cupertino_datetime_picker.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:nyh_motorcade_app/utils/toast_utils.dart';
import 'cash_flow_filter_controller.dart';
import 'package:nyh_motorcade_app/styles/colors.dart';
import 'package:nyh_motorcade_app/widgets/text_button_with_icon.dart';

typedef ValueCallback = void Function(
  String startDate,
  String endDate,
  String accountType,
  String transactionType,
);

typedef CloseCallback = void Function();

class CashFlowFilterPage extends StatelessWidget {
  final controller = Get.put(CashFlowFilterController());
  final ValueCallback onConfirm;
  final CloseCallback onClose;
  final bool showAccountTransactionType;

  CashFlowFilterPage({required this.onConfirm, required this.onClose, required this.showAccountTransactionType});

  @override
  Widget build(BuildContext context) {
    return Positioned(
      left: 0,
      top: 0,
      right: 0,
      bottom: 0,
      child: Column(
        children: [
          Container(
            height: showAccountTransactionType ? 395.w : 48.w +48.w + 48.w + 48.w + 10.w,
            color: Colours.color_white,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Expanded(
                  child: Scrollbar(
                    child: SingleChildScrollView(
                      physics: BouncingScrollPhysics(),
                      child: Column(
                        children: [
                          buildSelectDateTypeWidget(),
                          buildSelectStartDateWidget(),
                          buildSelectEndDateWidget(),
                          buildAccountTypeWidget(),
                          buildTransactionTypeWidget(),
                        ],
                      ),
                    ),
                  ),
                ),
                buildResetConfirmWidget(),
              ],
            ),
          ),
          Expanded(
            child: buildMarkWidget(),
          ),
        ],
      ),
    );
  }

  Widget buildSelectDateTypeWidget() {
    return Container(
      height: 48.w,
      padding: EdgeInsets.only(left: 16.w, right: 6.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            "时间类型",
            style: TextStyle(color: Colours.color_text_theme, fontSize: 14.sp),
          ),
          GetBuilder<CashFlowFilterController>(
            builder: (controller) {
              return TextButtonWithIcon(
                onPressed: () {
                  if (controller.dateType == DateType.day) {
                    controller.dateType = DateType.month;
                  } else {
                    controller.dateType = DateType.day;
                  }
                  controller.update();
                },
                icon: Image.asset("images/ic_change.png"),
                label: Text(
                  (controller.dateType == DateType.day) ? "按日选择" : "按月选择",
                  style: TextStyle(color: Colours.color_text_theme, fontSize: 14.sp),
                ),
                iconTextAlignment: IconTextAlignment.iconRightTextLeft,
                textIconPadding: 7.w,
                style: ButtonStyle(
                  tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                  minimumSize: MaterialStateProperty.all(Size(0, 0)),
                  padding: MaterialStateProperty.all(EdgeInsets.all(10.w)),
                ),
              );
            },
          ),
        ],
      ),
    );
  }

  Widget buildSelectStartDateWidget() {
    return Container(
      height: 48.w,
      padding: EdgeInsets.only(left: 16.w, right: 6.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            "开始日期",
            style: TextStyle(color: Colours.color_text_theme, fontSize: 14.sp),
          ),
          GetBuilder<CashFlowFilterController>(
            builder: (controller) {
              return TextButtonWithIcon(
                onPressed: () {
                  showDatePickerDialog(1);
                },
                icon: Image.asset("images/ic_arrow_right_gray.png", color: Colours.color_text_theme),
                label: Text(
                  (controller.dateType == DateType.day)
                      ? controller.startDayDate.isNotEmpty
                          ? controller.startDayDate
                          : "请选择"
                      : controller.startMonthDate.isNotEmpty
                          ? controller.startMonthDate
                          : "请选择",
                  style: TextStyle(color: Colours.color_text_theme, fontSize: 14.sp),
                ),
                iconTextAlignment: IconTextAlignment.iconRightTextLeft,
                textIconPadding: 7.w,
                style: ButtonStyle(
                  tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                  minimumSize: MaterialStateProperty.all(Size(0, 0)),
                  padding: MaterialStateProperty.all(EdgeInsets.all(10.w)),
                ),
              );
            },
          ),
        ],
      ),
    );
  }

  Widget buildSelectEndDateWidget() {
    return Container(
      height: 48.w,
      padding: EdgeInsets.only(left: 16.w, right: 6.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            "结束日期",
            style: TextStyle(color: Colours.color_text_theme, fontSize: 14.sp),
          ),
          GetBuilder<CashFlowFilterController>(
            builder: (controller) {
              return TextButtonWithIcon(
                onPressed: () {
                  showDatePickerDialog(2);
                },
                icon: Image.asset("images/ic_arrow_right_gray.png", color: Colours.color_text_theme),
                label: Text(
                  (controller.dateType == DateType.day)
                      ? controller.endDayDate.isNotEmpty
                          ? controller.endDayDate
                          : "请选择"
                      : controller.endMonthDate.isNotEmpty
                          ? controller.endMonthDate
                          : "请选择",
                  style: TextStyle(color: Colours.color_text_theme, fontSize: 14.sp),
                ),
                iconTextAlignment: IconTextAlignment.iconRightTextLeft,
                textIconPadding: 7.w,
                style: ButtonStyle(
                  tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                  minimumSize: MaterialStateProperty.all(Size(0, 0)),
                  padding: MaterialStateProperty.all(EdgeInsets.all(10.w)),
                ),
              );
            },
          ),
        ],
      ),
    );
  }

  Widget buildAccountTypeWidget() {
    return showAccountTransactionType
        ? Padding(
            padding: EdgeInsets.symmetric(vertical: 17.w, horizontal: 16.w),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  "账户类型",
                  style: TextStyle(color: Colours.color_text_theme, fontSize: 14.sp),
                ),
                SizedBox(
                  height: 17.w,
                ),
                MediaQuery.removePadding(
                  removeTop: true,
                  removeBottom: true,
                  context: Get.context!,
                  child: GetBuilder<CashFlowFilterController>(
                    builder: (controller) {
                      return GridView.builder(
                        itemCount: controller.accountTypeList.length,
                        shrinkWrap: true,
                        physics: BouncingScrollPhysics(),
                        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                          crossAxisCount: 3,
                          mainAxisSpacing: 10.w,
                          crossAxisSpacing: 16.w,
                          mainAxisExtent: 26.w,
                        ),
                        itemBuilder: (context, index) {
                          AccountType accountType = controller.accountTypeList[index];
                          String name = accountType.name;
                          bool isSelect = accountType.isSelect;
                          return TextButton(
                            onPressed: () {
                              controller.setSelectAccountType(accountType);
                            },
                            child: Text(
                              name,
                              style: TextStyle(color: isSelect ? Colours.color_theme : Colours.color_9fa0ab, fontSize: 12.sp),
                            ),
                            style: ButtonStyle(
                              tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                              backgroundColor: MaterialStateProperty.all(Colours.color_white),
                              shape: MaterialStateProperty.all(
                                RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(6.w),
                                  side: BorderSide(width: 1.w, color: isSelect ? Colours.color_theme : Colours.color_cfcfd5),
                                ),
                              ),
                              minimumSize: MaterialStateProperty.all(Size(0, 0)),
                              padding: MaterialStateProperty.all(EdgeInsets.all(0)),
                            ),
                          );
                        },
                      );
                    },
                  ),
                ),
              ],
            ),
          )
        : Container();
  }

  Widget buildTransactionTypeWidget() {
    return showAccountTransactionType
        ? Padding(
            padding: EdgeInsets.only(left: 16.w, right: 16.w, bottom: 17.w),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  "交易类型",
                  style: TextStyle(color: Colours.color_text_theme, fontSize: 14.sp),
                ),
                SizedBox(
                  height: 17.w,
                ),
                MediaQuery.removePadding(
                  removeTop: true,
                  removeBottom: true,
                  context: Get.context!,
                  child: GetBuilder<CashFlowFilterController>(
                    builder: (controller) {
                      return GridView.builder(
                        itemCount: controller.transactionTypeList.length,
                        shrinkWrap: true,
                        physics: BouncingScrollPhysics(),
                        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                          crossAxisCount: 3,
                          mainAxisSpacing: 10.w,
                          crossAxisSpacing: 16.w,
                          mainAxisExtent: 26.w,
                        ),
                        itemBuilder: (context, index) {
                          TransactionType transactionType = controller.transactionTypeList[index];
                          String name = transactionType.name;
                          bool isSelect = transactionType.isSelect;
                          return TextButton(
                            onPressed: () {
                              controller.setSelectTransactionType(transactionType);
                            },
                            child: Text(
                              name,
                              style: TextStyle(color: isSelect ? Colours.color_theme : Colours.color_9fa0ab, fontSize: 12.sp),
                            ),
                            style: ButtonStyle(
                              tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                              backgroundColor: MaterialStateProperty.all(Colours.color_white),
                              shape: MaterialStateProperty.all(
                                RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(6.w),
                                  side: BorderSide(width: 1.w, color: isSelect ? Colours.color_theme : Colours.color_cfcfd5),
                                ),
                              ),
                              minimumSize: MaterialStateProperty.all(Size(0, 0)),
                              padding: MaterialStateProperty.all(EdgeInsets.all(0)),
                            ),
                          );
                        },
                      );
                    },
                  ),
                ),
              ],
            ),
          )
        : Container();
  }

  Widget buildMarkWidget() {
    return GestureDetector(
      onTap: () {
        onClose();
      },
      child: Container(
        color: Colours.color_000000_80,
      ),
    );
  }

  Widget buildResetConfirmWidget() {
    return Container(
      height: 48.w,
      decoration: BoxDecoration(
        color: Colours.color_white,
        boxShadow: [
          BoxShadow(
            color: Colours.color_0f112e_95,
            offset: Offset(0.0, -2.w),
            blurRadius: 10.w,
          ),
        ],
      ),
      child: Row(
        children: [
          Expanded(
            child: TextButtonWithIcon(
              onPressed: () {
                controller.reset();
              },
              icon: Image.asset("images/ic_reset.png"),
              label: Text(
                "重置",
                style: TextStyle(
                  color: Colours.color_9fa0ab,
                  fontSize: 14.sp,
                ),
              ),
              textIconPadding: 3.w,
              style: ButtonStyle(
                minimumSize: MaterialStateProperty.all(Size(double.infinity, double.infinity)),
              ),
            ),
          ),
          Container(
            width: 1.w,
            height: double.infinity,
            color: Colours.color_background,
          ),
          Expanded(
            child: TextButton(
              onPressed: () {
                confirm();
              },
              child: Text(
                "确定",
                style: TextStyle(
                  color: Colours.color_theme,
                  fontSize: 14.sp,
                ),
              ),
              style: ButtonStyle(
                minimumSize: MaterialStateProperty.all(Size(double.infinity, double.infinity)),
              ),
            ),
          ),
        ],
      ),
    );
  }

  void confirm() {
    String startDate = "";
    String endDate = "";

    if (controller.dateType == DateType.day) {
      if (controller.startDayDate.isNotEmpty && controller.endDayDate.isNotEmpty) {
        startDate = controller.startDayDate;
        endDate = controller.endDayDate;
      } else if (controller.startDayDate.isEmpty && controller.endDayDate.isNotEmpty) {
        ToastUtils.toast("请选择开始日期");
        return;
      } else if (controller.endDayDate.isEmpty && controller.startDayDate.isNotEmpty) {
        ToastUtils.toast("请选择结束日期");
        return;
      }
    } else {
      if (controller.startMonthDate.isNotEmpty && controller.endMonthDate.isNotEmpty) {
        startDate = controller.startMonthDate + "-01";
        endDate = controller.endMonthDate + "-31";
      } else if (controller.startMonthDate.isEmpty && controller.endMonthDate.isNotEmpty) {
        ToastUtils.toast("请选择开始日期");
        return;
      } else if (controller.endMonthDate.isEmpty && controller.startMonthDate.isNotEmpty) {
        ToastUtils.toast("请选择结束日期");
        return;
      }
    }

    if (startDate.isNotEmpty && endDate.isNotEmpty) {
      if (DateTime.parse(endDate).isBefore(DateTime.parse(startDate))) {
        ToastUtils.toast("开始日期不能大于结束日期");
        return;
      }
    }

    onConfirm(startDate, endDate, controller.getSelectAccountType(), controller.getSelectTransactionType());
    onClose();
  }

  void showDatePickerDialog(int type) {
    DatePicker.showDatePicker(
      Get.context!,
      locale: DateTimePickerLocale.zh_cn,
      onMonthChangeStartWithFirstDate: true,
      pickerTheme: DateTimePickerTheme(
        cancelTextStyle: TextStyle(color: Colours.color_text_theme, fontSize: 14.sp),
        confirmTextStyle: TextStyle(color: Colours.color_text_theme, fontSize: 14.sp),
        itemTextStyle: TextStyle(color: Colours.color_text_theme, fontSize: 16.sp),
        titleHeight: 48.w,
        pickerHeight: 200.w,
        itemHeight: 40.w,
      ),
      dateFormat: controller.dateType == DateType.day ? "yyyy年-MM月-dd日" : "yyyy年-MM月",
      minDateTime: DateTime.parse("2021-01-01 00:00:00"),
      maxDateTime: DateTime.parse("2023-01-01 00:00:00"),
      onConfirm: (DateTime dateTime, List<int> selectedIndex) {
        String date = formatDate(dateTime, controller.dateType == DateType.day ? ["yyyy", "-", "mm", "-", "dd"] : ["yyyy", "-", "mm"]);
        if (controller.dateType == DateType.day) {
          //按日选择
          if (type == 1) {
            //开始日期
            controller.startDayDate = date;
          } else {
            //结束日期
            controller.endDayDate = date;
          }
        } else {
          //按月选择
          if (type == 1) {
            //开始日期
            controller.startMonthDate = date;
          } else {
            //结束日期
            controller.endMonthDate = date;
          }
        }
        controller.update();
      },
    );
  }
}
